package com.zwz.controller;

import com.zwz.bean.User;
import com.zwz.controller.jwt.JwtConfig;
import com.zwz.controller.util.DESUtils;
import com.zwz.controller.util.Result;
import com.zwz.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Alysia
 * @date 2022/11/7 10:20
 * @description 登录注册控制器类
 */

@RestController
@RequestMapping("/user")
public class LoginController {

    @Autowired
    private UserService userService;

    @Resource
    private JwtConfig jwtConfig;

    @Autowired
    private DESUtils desUtils;

    //用来处理用户登录
    @PostMapping("/login")
    public Result login(@RequestBody User user) throws Exception {
        String pwd = user.getUserPassword();
        user.setUserPassword(desUtils.encryptBaseDes(pwd));
        System.out.println(user);
        User userDB = userService.login(user);
        if (userDB != null) {
            String token = jwtConfig.createToken(userDB.getUserId());
            return Result.success(200, "登录成功", token);
        } else {
            return Result.error("用户不存在！");
        }

    }

    //用来处理用户注册
    @PostMapping("/register")
    public Result register(@RequestBody User user) {

        try {
            userService.register(user);
            return Result.success("注册成功！");
        } catch (Exception e) {
            return Result.error();
        }
    }
}
